package com.framework.auth.handler;

import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;
import java.util.*;

public final class SortedAuthoritiesFactory {

	public static final Set<GrantedAuthority> createSortedAuthorities(
			Collection<? extends GrantedAuthority> authorities) {

		SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<GrantedAuthority>(new AuthorityComparator());

		for (GrantedAuthority grantedAuthority : authorities) {
			sortedAuthorities.add(grantedAuthority);
		}

		return sortedAuthorities;
	}

	private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable {

		/** */
		private static final long serialVersionUID = 8198204239611555692L;

		@Override
		public int compare(GrantedAuthority g1, GrantedAuthority g2) {
			if (g2.getAuthority() == null) {
				return -1;
			}

			if (g1.getAuthority() == null) {
				return 1;
			}

			return g1.getAuthority().compareTo(g2.getAuthority());
		}

	}
}
